<template>
  <el-container style="height: 100vh;">
    <el-header>与蓝心大模型聊天</el-header>
    <el-main>
      <el-input
          type="textarea"
          v-model="message"
          placeholder="在这里输入你的消息...">
      </el-input>
      <el-button type="primary" @click="sendMessage">发送</el-button>
      <div v-for="msg in messages" :key="msg.id" class="message">
        {{ msg.content }}
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

export default {
  data() {
    return {
      message: '',
      messages: [],
      sessionId: uuidv4()
    };
  },
  methods: {
    sendMessage() {
      if (!this.message.trim()) {
        return;
      }
      const requestBody = {
        content: this.message,
        sessionId: this.sessionId
      };
      axios.post('/api/chat/send', requestBody)
          .then(response => {
            const responseData = response.data;
            if (responseData && responseData.data && responseData.code === 0) {
              this.messages.push({
                id: this.messages.length + 1,
                content: responseData.data.content
              });
              this.message = '';
            } else {
              console.error('接收到错误或格式无效:', responseData);
            }
          })
          .catch(error => {
            console.error('发送消息错误:', error);
            this.messages.push({
              id: this.messages.length + 1,
              content: `错误：${error.message || "与服务器通信失败"}`
            });
          });
    }
  }
}
</script>

<style scoped>
.message {
  margin: 10px 0;
}
</style>
